<template>
    <div class="article-list">
      <van-pull-refresh v-model="refreshing" @refresh="onRefresh" :success-text="successText" success-duration='1000'>
        <van-list
          v-model="loading"
          :finished="finished"
          finished-text="没有更多了"
          @load="onLoad"
          :error.sync="error"
          error-text="请求失败，点击重新加载">
          <article-item :articleItem='item' v-for="item in list" :key="item.art_id" ></article-item>
        </van-list>
      </van-pull-refresh>
    </div>
</template>

<script>
import { getChanelArticleList } from '@/api/user.js'
import articleItem from '../../../components/article-item.vue'
export default {
  name: 'articleList',
  data () {
    return {
      list: [],
      loading: false,
      finished: false,
      error: false,
      refreshing: false,
      timestamp: null,
      successText: ''
    }
  },
  props: {
    channel: {
      type: Object,
      required: true
    }
  },
  created () {

  },
  components: {
    articleItem
  },
  methods: {
    async onLoad () {
      try {
        const { data } = await getChanelArticleList({
          channel_id: this.channel.id,
          timestamp: this.timestamp || Date.now(),
          with_top: 1
        })
        // if (Math.random() > 0.5) {
        //   console.l('sdf')
        // }
        this.refreshing = false
        // console.log(data)
        this.list.push(...data.results)
        this.loading = false
        if (data.results.length) {
          this.timestamp = data.pre_timestamp
        } else {
          this.finished = true
        }
      } catch (err) {
        console.dir(err)
        this.error = true
        this.loading = false
      }
    },
    async onRefresh () {
      // 清空列表数据
      // this.finished = false
      // 重新加载数据
      // 将 loading 设置为 true，表示处于加载状态
      // this.loading = true
      try {
        const { data } = await getChanelArticleList({
          channel_id: this.channel.id,
          timestamp: Date.now(),
          with_top: 1
        })
        // if (Math.random() > 0.5) {
        //   console.l('sdf')
        // }
        this.successText = `更新成功了${data.results.length}条信息`
        this.list.unshift(...data.results)
        this.refreshing = false
        // this.loading = false
      } catch (err) {
        console.dir(err)
        this.$toast.fail('刷新错误')
        this.error = true
        this.refreshing = false
        // this.loading = false
        this.successText = '更新失败'
      }
    }
  }
}
</script>

<style scoped lang='less'>
 .article-list {
      height: 79vh;
      overflow: auto;
    }
</style>
